package NLP;

import com.hankcs.hanlp.classification.classifiers.NaiveBayesClassifier;
import com.hankcs.hanlp.classification.models.NaiveBayesModel;
import com.hankcs.hanlp.corpus.io.IOUtil;
import entity.SentimentResult;

import java.util.Map;

public class Sentiment {
    // 模型文件路径
    private String MODEL_PATH = "corpus\\sentiment\\modle.ser";
    private NaiveBayesModel model;

    private void loadModel(){
        model = (NaiveBayesModel) IOUtil.readObjectFrom(MODEL_PATH);
    }
    public Sentiment(){
        loadModel();
        if(model==null){
            System.err.println("模型文件加载失败");
        }
    }

    /**
     * 分析text的情感倾向, 0 < positive or negtive < 1
     * @param text
     * @return
     */
    public SentimentResult analysis(String text){
        NaiveBayesClassifier naiveBayesClassifier = new NaiveBayesClassifier(model);
        Map<String,Double> r = naiveBayesClassifier.predict(text);
        double posValue = r.get("p");
        double negValue = r.get("n");
        SentimentResult sentimentResult = new SentimentResult();
        sentimentResult.setPos(posValue);
        sentimentResult.setNeg(negValue);
        return sentimentResult;
    }
}
